
document.addEventListener('DOMContentLoaded', function() {
    // 默认加载首页
    fetch('pages/home.html').then(response => {
        return response.text();
    }).then(html => {
        document.querySelector('#content-container').innerHTML = html;
    }).then(async () => {
        const jsPath = "./home.js";
        const cssPath = "./css/home.css";
        const module = await import(jsPath);
        module.init();
        try {
            await loadCSS(cssPath);
            console.log("CSS loaded successfully!");
        } catch (error) {
            console.error("Failed to load CSS:", error);
        }
    }).catch(error => {
        console.error(error);
    });

    // 菜单项点击事件
    const menuItems = document.querySelectorAll('.menu-item');
    menuItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有active类
            menuItems.forEach(i => {
                i.classList.remove('active');
            });
            // 添加active类到当前项
            this.classList.add('active');
            // 加载对应页面
            const page = this.getAttribute('data-page');
            const id = this.getAttribute('data-id');
            loadContent(page,id);

        });

    // 用户头像点击事件
    document.querySelector('.user-avatar').addEventListener('click', function() {
        alert('将显示用户菜单或跳转到个人中心');
    });
    });
});

export function loadContent(page,id){
    fetch(page).then(response => {
        return response.text();
    }).then(html => {
        document.querySelector('#main-content').innerHTML = html;
    }).then(async () => {
        const jsPath = "./"+id+".js";
        const cssPath = "./css/"+id+".css";
        const module = await import(jsPath);
        module.init();
        try {
            await loadCSS(cssPath);
            console.log("CSS loaded successfully!");
        } catch (error) {
            console.error("Failed to load CSS:", error);
        }
    }).catch(error => {
        console.error(error);
    });
}

function loadCSS(url) {
    return new Promise((resolve, reject) => {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = url;
        link.onload = resolve;
        link.onerror = reject;
        document.head.appendChild(link);
    });
}
